package com.ygqh.baby.controller;

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.annotation.WebLog;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.Constant;
import com.ygqh.baby.ao.CustomerStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.MessageType;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.model.ChatRecord;
import com.ygqh.baby.model.CustomerUser;
import com.ygqh.baby.model.QuickReply;
import com.ygqh.baby.model.YgOrderInfoModel;
import com.ygqh.baby.model.YgOrderModel;
import com.ygqh.baby.model.YgReturnOrderInfoModel;
import com.ygqh.baby.model.YgReturnOrderModel;
import com.ygqh.baby.model.YgUserModel;
import com.ygqh.baby.po.YgReturnOrderLog;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.ChatRecordService;
import com.ygqh.baby.service.CustomerUserService;
import com.ygqh.baby.service.QuickReplyService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.YgReturnOrderLogService;
import com.ygqh.baby.service.YgReturnOrderService;
import com.ygqh.baby.service.YgUserService;

/**
 * @author Ss
 */
@Controller
@RequestMapping("/chat/customer")
public class CustomerUserController extends BaseController {

	private final CustomerUserService customerUserService;
	private final YgUserService ygUserService;
	private final ChatRecordService chatRecordService;
	private final YgOrderService ygOrderService;
	private final QuickReplyService quickReplyService;
	private final YgReturnOrderService ygReturnOrderService;
	private final YgReturnOrderLogService ygReturnOrderLogService;

	@Autowired
	public CustomerUserController(CustomerUserService customerUserService, YgUserService ygUserService, ChatRecordService chatRecordService,
								  YgOrderService ygOrderService, QuickReplyService quickReplyService, YgReturnOrderService ygReturnOrderService,
								  YgReturnOrderLogService ygReturnOrderLogService) {
		this.customerUserService = customerUserService;
		this.ygUserService = ygUserService;
		this.chatRecordService = chatRecordService;
		this.ygOrderService = ygOrderService;
		this.quickReplyService = quickReplyService;
		this.ygReturnOrderService = ygReturnOrderService;
		this.ygReturnOrderLogService = ygReturnOrderLogService;
	}

	/**
	 * 获取当前客服信息
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping("/getCurrentCustomerInfo")
	@ResponseBody
	public JSONPObject getCurrentCustomerInfo(String callback) {
		return new JSONPObject(callback, Message.success(customerUserService.findByUserName(getSessionUser().getUserName())));
	}

	/**
	 * 修改当前客服在线状态
	 *
	 * @param customerStatus
	 * @param callback
	 * @return
	 */
	@WebLog("修改当前客服在线状态")
	@RequestMapping("/updateCurrentCustomerStatus")
	@ResponseBody
	public JSONPObject updateCurrentCustomerStatus(CustomerStatus customerStatus, String callback) {
		return new JSONPObject(callback, customerUserService.updateCustomerStatus(getSessionUser().getUserName(), customerStatus));
	}

	/**
	 * 获取指定用户信息
	 *
	 * @param userId
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findYgUserInfo")
	@ResponseBody
	public JSONPObject findYgUserInfo(Long userId, String callback) {
		CustomerUser customerUser = customerUserService.findByUserName(getSessionUser().getUserName());
		for (YgUserModel ygUser : customerUser.getUserList()) {
			if (ygUser.getId().equals(userId)) {
				return new JSONPObject(callback, Message.success(ygUser));
			}
		}
		return new JSONPObject(callback, Message.success(ygUserService.findUserById(userId)));
	}

	/**
	 * 获取用户列表
	 *
	 * @param q
	 * @param callback
	 * @param isStar
	 * @return
	 */
	@RequestMapping("/findUserList")
	@ResponseBody
	public JSONPObject findUserList(String q, String callback, Boolean isStar) {
		CustomerUser findByUserId = customerUserService.findByUserName(getSessionUser().getUserName());
		List<YgUserModel> userList;
		if (StringUtils.isBlank(q)) {
			if (isStar != null && isStar) {
				userList = customerUserService.findUserListByIsStar(Boolean.TRUE);
			} else {
				userList = customerUserService.findUserList(findByUserId);
			}
		} else {
			userList = customerUserService.searchUserList(q);
		}
		return new JSONPObject(callback, Message.success(userList));
	}

	/**
	 * 获取指定用户历史聊天记录
	 *
	 * @param queryInfo
	 * @param userId
	 * @param q
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findRecordList")
	@ResponseBody
	public JSONPObject findRecordList(QueryInfo queryInfo, Long userId, String q, String callback) {
		List<Long> userIdList;
		if (userId == null) {
			userIdList = null;
		} else {
			userIdList = Collections.singletonList(userId);
		}
		return new JSONPObject(callback,
				Message.success(chatRecordService.findUserRecordList(userIdList, q, queryInfo)));
	}

	/**
	 * 获取其他在线客服
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findOtherCustomerList")
	@ResponseBody
	public JSONPObject findOtherCustomerList(String callback, CustomerStatus customerStatus) {
		logger.info("获取其他在线客服, customerStatus={}", customerStatus);
		List<CustomerUser> findCustomerList = customerUserService
				.findCustomerList(getSessionUser().getUserName(), Boolean.FALSE, customerStatus);
		return new JSONPObject(callback, Message.success(findCustomerList));
	}

	/**
	 * 把用户转接给其他客服
	 *
	 * @param userId
	 * @param customerId
	 * @param callback
	 * @return
	 */
	@WebLog("把用户转接给其他客服")
	@RequestMapping("/speakCurrentUser")
	@ResponseBody
	public JSONPObject speakCurrentUser(Long userId, String customerId, String callback) {
		if (userId == null) {
			return new JSONPObject(callback, Message.error(Constant.UNSPECIFIED_USER));
		}
		YgUserModel sessionUser = getSessionUser();
		logger.info("把用户转接给其他客服, userId={}, customerId={}, operator={}", userId, customerId, sessionUser.getNickName());
		CustomerUser currentCustomer = customerUserService.findByUserName(sessionUser.getUserName());
		return new JSONPObject(callback, customerUserService.updateUserToOtherCustomer(currentCustomer.getId(),
				customerId, userId));
	}

	/**
	 * 修改用户星标
	 *
	 * @param userId
	 * @param isStar
	 * @param callback
	 * @return
	 */
	@WebLog("修改用户星标")
	@RequestMapping("/updateUserByIsStar")
	@ResponseBody
	public JSONPObject updateUserByIsStar(Long userId, Boolean isStar, String callback) {
		if (userId == null) {
			return new JSONPObject(callback, Message.error(Constant.UNSPECIFIED_USER));
		}
		logger.info("修改用户星标, userId={}, isStar={}, operator={}", userId, isStar, getSessionUser().getNickName());
		return new JSONPObject(callback, customerUserService.updateUserByIsStar(null, userId, isStar));
	}

	/**
	 * 获取快捷回复信息列表
	 *
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findQuickReplyList")
	@ResponseBody
	public JSONPObject findQuickReplyList(String callback) {
		return new JSONPObject(callback, Message.success(quickReplyService.findQuickReplyList()));
	}

	/**
	 * 发送欢迎语
	 *
	 * @param callback
	 * @return
	 */
	@WebLog("发送欢迎语")
	@RequestMapping("/sendWelcome")
	@ResponseBody
	public JSONPObject sendWelcome(Long userId, String callback) {
		if (userId == null) {
			return new JSONPObject(callback, Message.error(Constant.UNSPECIFIED_USER));
		}
		List<QuickReply> qList = quickReplyService.findQuickReplyList();
		for (QuickReply quickReply : qList) {
			if (quickReply.getIsFirst()) {
				return this.saveCustomerRecord(quickReply.getDetailContent(), null, quickReply.getMessageType(), userId, false, callback);
			}
		}
		return new JSONPObject(callback, Message.error(Constant.TRY_AGAIN_LATER));
	}

	/**
	 * 保存客服发送的信息
	 *
	 * @param detailContent
	 * @param messageType
	 * @param userId
	 * @param callback
	 * @return
	 */
	@WebLog("保存客服发送的信息")
	@RequestMapping("/saveCustomerRecord")
	@ResponseBody
	public JSONPObject saveCustomerRecord(String detailContent, String originalImage, MessageType messageType, Long userId, boolean sendWxMsg, String callback) {
		if (userId == null) {
			return new JSONPObject(callback, Message.error(Constant.UNSPECIFIED_USER));
		}
		YgUserModel sessionUser = getSessionUser();
		logger.info("客服发送的信息, detailContent={}, originalImage={}, messageType={}, userId={}, sendWxMsg={}, operator={}", 
				detailContent, originalImage, messageType, userId, sendWxMsg, sessionUser.getNickName());
		CustomerUser customerUser = customerUserService.findByUserName(sessionUser.getUserName());
		ChatRecord chatRecord = new ChatRecord();
		chatRecord.setUserId(userId);
		chatRecord.setDetailContent(detailContent);
		chatRecord.setOriginalImage(originalImage);
		chatRecord.setCreateTime(new Date());
		chatRecord.setMessageType(messageType);
		List<YgUserModel> findUserList = customerUserService.findUserList(customerUser);
		boolean isExists = false;
		if (CollectionUtils.isNotEmpty(findUserList)) {
			for (YgUserModel ygUser : findUserList) {
				if (!ygUser.getId().equals(userId)) {
					continue;
				}
				chatRecord.setUserNickName(ygUser.getNickName());
				chatRecord.setReceiveHeadId(ygUser.getHeadFileId());
				chatRecord.setReceiveNickName(ygUser.getNickName());
				chatRecord.setReceiveUserId(userId.toString());
				if (sendWxMsg && !ygUser.getIsOnline() && messageType.equals(MessageType.Text)) {
					//用户不在线并且是文本消息，发送微信消息
					/*chatRecordService.sendTemplateMessage(ygUser.getOpenId(), chatRecord);*/
					chatRecordService.sendSms(ygUser.getUserName(), chatRecord);
				}
				isExists = true;
				break;
			}
		}
		if (!isExists) {
			YgUser ygUser = ygUserService.findUserById(userId);
			if (ygUser != null) {
				String saveHeadImageToMongo = ygUserService.saveHeadImageToMongo(ygUser.getHeadImageUrl(), ygUser.getUserName());
				chatRecord.setReceiveHeadId(saveHeadImageToMongo);
				chatRecord.setReceiveNickName(ygUser.getNickName());
				chatRecord.setReceiveUserId(userId.toString());
				if (sendWxMsg && messageType.equals(MessageType.Text)) {
					//用户不在线并且是文本消息，发送微信消息
					/*chatRecordService.sendTemplateMessage(ygUser.getOpenId(), chatRecord);*/
					chatRecordService.sendSms(ygUser.getUserName(), chatRecord);
				}
			}
		}
		chatRecord.setSendHeadId(customerUser.getHeadFileId());
		chatRecord.setSendNickName(StringUtils.isNotBlank(customerUser.getTrueName()) ? customerUser.getTrueName() : customerUser.getNickName());
		chatRecord.setSendUserId(customerUser.getId());
		chatRecordService.save(chatRecord);
		return new JSONPObject(callback, Message.success(chatRecord));
	}

	/**
	 * 更新消息已读
	 *
	 * @param callback
	 * @return
	 */
	@WebLog("更新消息已读")
	@RequestMapping("/readRecord")
	@ResponseBody
	public JSONPObject readRecord(Long userId, String callback) {
		YgUserModel currentUser = getSessionUser();
		logger.info("更新消息已读, userId={}, operator={}", userId, currentUser.getNickName());
		return new JSONPObject(callback, chatRecordService.updateChatRecordToRead(userId.toString(), null, currentUser));
	}

	/**
	 * 获取指定用户全部有效订单
	 *
	 * @param userId
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findOrderListByUserId")
	@ResponseBody
	public JSONPObject findOrderListByUserId(Long userId, String callback) {
		if (userId == null) {
			return new JSONPObject(callback, Message.error(Constant.UNSPECIFIED_USER));
		}
		List<YgOrderModel> orderList = ygOrderService.findOrderList(userId);
		return new JSONPObject(callback, Message.success(orderList));
	}

	/**
	 * 获取订单详情
	 *
	 * @param orderId
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findOrderInfo")
	@ResponseBody
	public JSONPObject findOrderInfo(Long orderId, String callback) {
		if (orderId == null) {
			return new JSONPObject(callback, Message.error("未指定订单"));
		}
		YgOrderInfoModel model = ygOrderService.findOrderInfo(orderId);
		return new JSONPObject(callback, Message.success(model));
	}

	/**
	 * 获取指定用户退换货订单列表
	 *
	 * @param userId
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findReturnList")
	@ResponseBody
	public JSONPObject findReturnList(Long userId, String callback) {
		List<YgReturnOrderModel> returnOrderList = ygReturnOrderService.findReturnList(userId, 20);
		return new JSONPObject(callback, Message.success(returnOrderList));

	}

	/**
	 * 获取退换货单详细
	 *
	 * @param returnCode
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findReturnOrderInfo")
	@ResponseBody
	public JSONPObject findReturnOrderInfo(String returnCode, String callback) {
		YgReturnOrderInfoModel orderInfo = ygReturnOrderService.findReturnOrderInfo(returnCode, null);
		return new JSONPObject(callback, Message.success(orderInfo));
	}

	/**
	 * 获取退换货进度
	 *
	 * @param returnCode
	 * @param callback
	 * @return
	 */
	@RequestMapping("/findReturnScheduleList")
	@ResponseBody
	public JSONPObject findReturnScheduleList(String returnCode, String callback) {
		List<YgReturnOrderLog> list = ygReturnOrderLogService.findReturnScheduleList(returnCode);
		Message msg = Message.success(list);
		return new JSONPObject(callback, msg);

	}

	private YgUserModel getSessionUser() {
		Subject subject = SecurityUtils.getSubject();
		return (YgUserModel) subject.getPrincipal();
	}

	/**
	 * 删除客服下指定用户的匹配关系
	 *
	 * @param userIds
	 * @param callback
	 * @return
	 */
	@WebLog("删除客服下指定用户的匹配关系")
	@RequestMapping("/deleteUserFromCustomer")
	@ResponseBody
	public JSONPObject deleteUserFromCustomer(Long[] userIds, String callback) {
		if (userIds == null || userIds.length == 0) {
			return new JSONPObject(callback, Message.error("待删除用户id为空", null));
		}
		YgUserModel sessionUser = getSessionUser();
		logger.info("删除用户, userIds={}, operator={}", Arrays.asList(userIds), sessionUser.getNickName());
		return new JSONPObject(callback, customerUserService.deleteUserFromCustomer(userIds, sessionUser.getUserName()));
	}

}
